import React, { PureComponent, Fragment } from 'react';
import { message } from 'antd';
import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Button,
  Divider,
  Tooltip,
  Select,
} from 'antd';
import isEqual from 'lodash/isEqual';
import { connect } from 'dva';
import { formatMessage } from 'umi/locale';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber max={this.props.max} min={this.props.min} step={this.props.step} />;
    }
    if (this.props.inputType === 'select') {
      {
        if (this.props.dataIndex == 'jointNumber') {
          return (
            <Select>
              <Select.Option value="4">四拼板</Select.Option>
              <Select.Option value="6">六拼板</Select.Option>
            </Select>
          );
        }
        if (this.props.dataIndex == 'lengthUnit') {
          return (
            <Select>
              <Select.Option value={formatMessage({ id: 'app.produce.mm' })}>
                {' '}
                {formatMessage({ id: 'app.produce.mm' })}
              </Select.Option>
              <Select.Option value={formatMessage({ id: 'app.produce.inch' })}>
                {formatMessage({ id: 'app.produce.inch' })}
              </Select.Option>
            </Select>
          );
        }
      }
    }
    return <Input />;
  };

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      max,
      min,
      step,
      ...restProps
    } = this.props;
    return (
      <EditableContext.Consumer>
        {form => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [
                      {
                        required: true,
                        message: `请输入${title}!`,
                      },
                    ],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : (
                restProps.children
              )}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

@connect(({ produce, os }) => ({ produce, os }))
class OrderForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { editingKey: '', order: {}, pagination: false };
    this.columns = [
      {
        title: '物料号',
        dataIndex: 'cutId',
        width: '8%',
        editable: true,
        inputType: 'string',
      },
      {
        title: '板宽',
        dataIndex: 'width',
        editable: true,
        width: '8%',
        max: 750,
        min: 200,
        step: 0.1,
        inputType: 'number',
      },
      {
        title: '板高',
        dataIndex: 'height',
        editable: true,
        width: '8%',
        max: 650,
        min: 200,
        step: 0.1,
        inputType: 'number',
      },
      {
        title: '几拼板',
        dataIndex: 'jointNumber',
        editable: true,
        width: '10%',
        inputType: 'select',
      },
      // {
      //   title: '作业去向',
      //   dataIndex: 'toWhere',
      //   editable: true,
      //   width: '9.09%',
      //   inputType: 'select',
      // },
      {
        title: '作业开始时间',
        dataIndex: 'workBegin',
        editable: false,
        width: '10%',
        max: 50,
        min: 1,
        step: 1,
        inputType: 'string',
      },
      {
        title: '最后作业时间',
        dataIndex: 'workEnd',
        editable: false,
        width: '10%',
        max: 50,
        min: 1,
        step: 1,
        inputType: 'string',
      },
      {
        title: '时间段作业数量',
        dataIndex: 'workAmount',
        editable: false,
        width: '12%',
        max: 10000000,
        min: 0,
        step: 1,
        inputType: 'number',
      },
      {
        title: '本工单已加工数量',
        dataIndex: 'amount',
        editable: false,
        width: '12%',
        max: 10000000,
        min: 1,
        step: 1,
        inputType: 'number',
      },
      {
        title: '操作',
        key: 'action',
        width: '10%',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.save(form, record.key)}
                        style={{ marginRight: 8 }}
                      >
                        保存
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.key)}>
                    <a>取消</a>
                  </Popconfirm>
                </span>
              ) : (
                <span>
                  <a onClick={() => this.edit(record.key)}>编辑</a>
                  <Divider type="vertical" />
                  <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.key)}>
                    <a>删除</a>
                  </Popconfirm>
                </span>
              )}
            </div>
          );
        },
      },
    ];
  }
  newMember = () => {
    if (this.state.editingKey === '') {
      var myDate = new Date();
      const { workingOrder } = this.props.os;
      const { dispatch } = this.props;
      const newData = {
        key: myDate.getTime(),
        lengthUnit: 'mm',
        width: 600,
        height: 600,
        jointNumber: "4",
        amount: 0,
        workAmount: 0,
        // toWhere: "平板车1",
        workBegin: '00-00-00',
        workEnd: '00-00-00',
        firstTime: true,
      };
      this.setState({ order: newData });
      const newServerOrder = [newData];
      console.log('newServerOrder', newServerOrder);
      dispatch({
        type: 'os/addServerOrder',
        payload: newServerOrder,
      });
      this.edit(newData.key);
    }
  };
  isEditing = record => record.key === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
    const { dispatch } = this.props;
    dispatch({
      type: 'hd/getServerOrder',
    });
  };
  handleOnRow = record => {
    const { dispatch } = this.props;
    return {
      //   onClick: (event) => {console.log("record",record)},       // 点击行
      onDoubleClick: event => {
        dispatch({
          type: 'os/updateChooseOrder',
          payload: [record],
        });
      },
    };
  };
  save(form, key) {
    const { dispatch } = this.props;
    const { order } = this.state;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = { ...order, ...row, key: key };
      // console.log("newData",newData);
      this.setState({ order: {} });
      this.edit('');
      dispatch({
        type: 'os/saveOrder',
        payload: newData,
      });

      dispatch({
        type: 'produce/updateOrder',
        payload: newData,
      });
    });
  }

  remove(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'os/deleteOrder',
      payload: key,
    });
  }

  edit(key) {
    // const { min_edge } = this.props.hd;
    this.setState({ editingKey: key });
  }

  render() {
    const { workingOrder, totalOrders, showTotalOrdersFlag } = this.props.os;
    let showData;
    if (showTotalOrdersFlag) {
      showData = totalOrders;
    } else {
      showData = workingOrder;
    }
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.inputType,
          dataIndex: col.dataIndex,
          max: col.max,
          min: col.min,
          step: col.step,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Fragment>
        <Table
          components={components}
          bordered
          dataSource={showData}
          pagination={showTotalOrdersFlag}
          columns={columns}
          rowClassName="editable-row"
          size={'small'}
          onRow={this.handleOnRow}
          footer={() =>
            Object.keys(this.props.order).length > 0 ? (
              <h6>
                已选中：<font style={{ color: '#FF0000' }}>{workingOrder[0].cutId}</font>
              </h6>
            ) : (
              <h6>*请双击需要加工的工单</h6>
            )
          }
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.newMember}
          icon="plus"
        >
          添加工单
        </Button>
      </Fragment>
    );
  }
}

export default OrderForm;
